package servlet;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

// 添加注解
@MultipartConfig
@WebServlet("/upload")
public class UploadServlet extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1.得到参数
		String username = req.getParameter("username");
		System.out.println("用户名是:" + username);
		//2.得到上传文件部分
		Part part = req.getPart("uploadfile");
		//3.得到上传的文件名
		String fileName = part.getSubmittedFileName();
		//4.得到发布以后upload目录的绝对位置
		String realPath = this.getServletContext().getRealPath("/upload");
		System.out.println("上传文件位置:" + realPath);
		//5.把文件保存到服务器上 
		/*
		 * arg0: part.getInputStream()这个流里就是上传的文件内容
		 * arg1: 拷贝到目标位置(父路径,文件名)
		 * arg2: 文件拷贝的参数，文件存在就替换
		 */
		Files.copy(part.getInputStream(), 
				Paths.get(realPath, fileName), 
				StandardCopyOption.REPLACE_EXISTING);
	
	}
}
